package com.xm.xm.undercover.utils

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.xm.xm.undercover.R
import com.xm.xm.undercover.bean.Msg
import com.xm.xm.undercover.ui.RoomActivity
import kotlinx.android.synthetic.main.activity_room.view.*
import kotlinx.android.synthetic.main.msg_left_item.view.*
import kotlinx.android.synthetic.main.msg_right_item.view.*

class MsgAdapter (val msgList:List<Msg>):RecyclerView.Adapter<RecyclerView.ViewHolder>(){

    inner class LeftViewHolder(view: View):RecyclerView.ViewHolder(view){
        val leftMsg:TextView = view.findViewById(R.id.leftMsg)
    }
    inner class RightViewHolder(view: View):RecyclerView.ViewHolder(view){
        val rightMsg:TextView = view.findViewById(R.id.rightMsg)
    }

    override fun getItemViewType(position: Int): Int {
        val msg = msgList[position]
        return msg.fromIndex.toInt()
    }

    private val userImage = arrayOf(R.drawable.rob,R.mipmap.tx1,R.mipmap.tx2,R.mipmap.tx3,R.mipmap.tx4,R.mipmap.tx5,R.mipmap.tx6,R.mipmap.tx7,R.mipmap.tx8)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = if (viewType != UserInfo.curUserIndex.toInt()) {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.msg_left_item,parent,false)
        view.leftUser.setImageResource(userImage[viewType])
        if (viewType==0){
            view.leftName.text = UserInfo.u0
        }
        else {
            view.leftName.text = RoomActivity.everyone[viewType - 1]
        }
        LeftViewHolder(view)
    }
    else{
        val view = LayoutInflater.from(parent.context).inflate(R.layout.msg_right_item,parent,false)
        view.rightUser.setImageResource(userImage[viewType])
        RightViewHolder(view)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val msg = msgList[position]
        when (holder){
            is LeftViewHolder -> holder.leftMsg.text = msg.content
            is RightViewHolder -> holder.rightMsg.text = msg.content
            else -> throw IllegalArgumentException()
        }
    }


    override fun getItemCount() = msgList.size
}